#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "log.hpp"

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << argv[0] << "[ip]" << "[port]" << std::endl;
        return -1;
    }
    // 获取命令行参数
    uint16_t port = stoi(argv[2]);
    string ip = argv[1];
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    

        
    while (1)
    {
        // socket
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            std::cout << "client create fail" << endl;
            exit(1);
        }
        // bind由os随机分配端口完成
        
        // connect
        int n = connect(sockfd, (struct sockaddr *)&server, (socklen_t)sizeof(server));
        if (n < 0)
        {
            std::cout << "client connect fail" << std::endl;
            exit(2);
        }

        std::string msg;
        std::cout << "Please Enter>_";
        getline(std::cin, msg);
        // 发送数据
        n = write(sockfd, msg.c_str(), msg.size());
        if (n < 0)
        {
            std::cout << "write fail" << std::endl;
            continue;
        }
        char buf[1024] = {0};
        // 接收数据
        n = read(sockfd, buf, sizeof(buf));
        if (n < 0)
        {
            std::cout << "read fail" << std::endl;
            continue;
        }
        buf[n] = 0;
        cout << buf << endl;
    }
}